<?php

/**
 * 处理导入模型&词条
 * 约定目录内不存在的删除
 */

namespace App\Console\Commands;

use App\Datas\ModelList;
use App\Datas\ModelStyle;
use Illuminate\Console\Command;

use App\Tools\File;
use Illuminate\Support\Facades\DB;

class handleModelStyleSafeCommand extends BaseCommand {
	/**
	 * 命令行执行命令
	 * @var string
	 */
	protected $signature = 'handleModelStyleSafe';

	/**
	 * 命令描述
	 *
	 * @var string
	 */
	protected $description = 'handle model style list';

	public function handle() {
		$aImportAmount = [];
		$sCsvFile = $this->rootPath.'/storage/tmp/safe.csv';
		$aStyleList = $this->_getCSVFile($sCsvFile);

		if(empty($aStyleList)) {
			echo 'CSV 文件空'.PHP_EOL;
			exit;
		}

		echo 'Start'.PHP_EOL;
		$iModelID = 0;
		foreach($aStyleList as $aStyle) {
			if(empty($aStyle)) {
				continue;
			}

			$_iModelID = trim($aStyle[0]);
			if(!empty($_iModelID)) {
				$iModelID = $_iModelID;

				$_aWhere = ['id' => $iModelID];
				$_aUpdate = ['is_safe' => 1];
				ModelList::getInstance()->editModelByWhere($_aWhere, $_aUpdate);
			}

			$sFile = trim($aStyle[1]);
			$sFile = pathinfo($sFile, PATHINFO_FILENAME);
			$sFile .= '.webp';

			$sFilePath = '/style/'.$iModelID.'/'.$sFile;

			$_aWhere = ['model_id' => $iModelID, 'img' => $sFilePath];
			$_aUpdate = ['is_safe' => 1];
			ModelStyle::getInstance()->editModelByWhere($_aWhere, $_aUpdate);

			if(isset($aImportAmount[$iModelID])) {
				$aImportAmount[$iModelID] += 1;
			} else {
				$aImportAmount[$iModelID] = 1;
			}
		}
		echo 'End'.PHP_EOL;

		var_dump($aImportAmount);
		exit;
	}

	/**
	 * 读取CSV文件
	 * @param string $sFile
	 * @return array|false
	 */
	private function _getCSVFile($sFile) {
		if(!file_exists($sFile)) {
			return false;
		}
		$oFOpen = fopen($sFile, 'rb');
		$aDataList = [];
		while(!feof($oFOpen)) {
			$aDataList[] = fgetcsv($oFOpen);
		}
		fclose($oFOpen);
		return $aDataList;
	}


}